﻿using System;
using SeventhHabit.Dbm.Model;

namespace SeventhHabit.Dbm.Console {
    internal class Program {
        #region Readonly & Static Fields

        private static string UpgradeHelpText =
            "Syntax to run an upgrade is /u:[sql|ce] \"connection string\" \"script folder path\"";

        #endregion

        #region Class Methods

        private static IVersionedDatabase GetDatabase(string[] args) {
            IVersionedDatabase database;
            switch (args[1].ToLower()) {
                case "sql":
                    database = GetSqlDatabase(args[2]);
                    break;
                case "ce":
                    database = GetSqlCeDatabase(args[2]);
                    break;
                default:
                    database = null;
                    break;
            }
            return database;
        }

        private static IVersionedDatabase GetSqlCeDatabase(string connectionString) {
            return new SqlCeDatabase(connectionString);
        }

        private static IVersionedDatabase GetSqlDatabase(string connectionString) {
            return new SqlServerDatabase(connectionString);
        }

        private static void Main(string[] args) {
            if (args.Length == 0) {
                PrintHelp();
                return;
            }

            try {
                switch (args[0].ToLower()) {
                    case "/u":
                        RunUpgrade(args);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex) {
                System.Console.WriteLine(ex.Message);
                PrintHelp();
            }
        }

        private static void PrintHelp() {
            System.Console.WriteLine(UpgradeHelpText);
        }

        private static void RunUpgrade(string[] args) {
            if (args.Length != 4) {
                PrintHelp();
                return;
            }

            IVersionedDatabase database = GetDatabase(args);
            if (database != null) {
                IScriptRunner scriptRunner = new ScriptRunner(database);
                UpgradeDatabase(scriptRunner, args[3]);
            }
            else
                PrintHelp();
        }

        private static void UpgradeDatabase(IScriptRunner scriptRunner, string scriptFolder) {
            var manager = new DbManager(scriptRunner);
            manager.UpgradeDatabase(scriptFolder);
        }

        #endregion
    }
}